<?php
include '../../../common.inc.php';
include __DIR__ .'/qs.funcs.php';

// 起始ID
if (!isset($start)) {
	$start = 0;
}

// 结束ID
if (!isset($end)) {
	exit(qsLang('NO_END'));
}
if ($start>$end) {
	exit(qsLang('HANDLE_OVER'));
}
if (!isset($num)) {
	$num = 50;
}

$curEnd = $start+$num;

// 是否重新处理

$db = new DbMysqli();
$db->connect('192.168.1.19', 'root', 'root', 'ixdcw', 0, 'UTF8');
$db->setPre('xd_');

$redo = isset($redo) ? $redo : 0;
if (!$redo) {
	$strRedo = "and ok = 0";
} else {
	$strRedo = '';
}

$sql = "select * from {$db->getPre()}qs_answer where  {$start} < id and id<= $end {$strRedo} order by id ASC limit " . $num;
$res = $db->getAll($sql);

// 检测是否处理完成
if (!$res) {
	exit(qsLang('HANDLE_OVER'));
}
var_dump($res[0]);
$rule = DT_ROOT . '/file/dict/rules.utf8.ini' ;
$dict = DT_ROOT . '/file/dict/car.dict.utf8.xdb' ;
$scws = new SCWS(SCWS::CHARSET_UTF8, $rule, $dict);
$nokwFile = __DIR__ .'/noKw.txt';
$nokwContent = '';
$idin = array();
foreach($res as $v) {
	$idin[] = $v['id'];
	$scws->setText($v['title']);
	$kws = $scws->getTops();
	if ($kws) {
		$kwin = array();
		foreach($kws as $kw) {
			// 插入关键词
			$kwin[] = "{$kw['word']}";
			$sql = "insert into {$db->getPre()}qs_keyword (keyword) values('{$kw['word']}')";
			$db->query($sql);
		}
		// 更新关键词链接
		$ids = $db->getCol("select id from {$db->getPre()}qs_keyword where keyword in ('" . implode("','", $kwin) ."')", 'id');
		$db->query("delete from {$db->getPre()}qs_relation where aid={$v['id']}");
		$sql = "insert into {$db->getPre()}qs_relation (aid, kwid) values";
		foreach($ids as $kwid) {
			$sql .= "({$v['id']}, {$kwid}),";
		}
		$sql = rtrim($sql, ',');
		if (!$db->query($sql)) {
			exit($db->error());
		}
	} else {
		$nokwContent .= "{$v['id']}\n";
	}

}
$db->query("update {$db->getPre()}qs_answer set ok=1 where id in (".implode(',',$idin).")");
file_put_contents($nokwFile, file_get_contents($nokwFile).$nokwContent);
echo '<meta http-equiv="refresh" content="0; url='.$_SERVER['PHP_SELF'].'?start='.$curEnd.'&end='.$end.'&redo='.$redo.'" />';